#encoding:utf8 


import os, sys, json
sys.path.append(os.path.dirname(os.getcwd()))
from inc.dbmgr import DbMgr
from inc.dlmgr import DlMgr
from srer.douban import DoubanSr

from funcs import get_dbcolt_list

# ==============
# 库中字段格式化
# ==============

def strip_col_string(dbcollection, colname, callback):
	booklist = get_dbcolt_list(dbcollection)
	for ret in booklist:
		bname = ret[colname]
		fname = bname.strip() 
		dbcollection.update({colname:bname}, {"$sets":{colname:fname}})
	if callback:
		callback()

# =================
# 库中豆瓣评分更新
# =================

def sr_doubanbook_score(dbcollection, callback = None):
	course = dbcollection.find()
	sr = DoubanSr("book")

	def iteration(cursor):
		ret = cursor.next()
		if ret:
			sr.search(ret['name'])
	        star = sr.get_ret()["score"]
	       	dbcollection.update({"name":ret["name"]}, {"$set":{"douban_star":star}})
	        try:
        		iteration(cursor)
	        except:
	        	if callback:
	        		callback()
	iteration(course)	

#test-
'''
db = DbMgr(host= MONGO["HOST"], port=MONGO["PORT"])
db.use("kankindle")
collection = db.use_collection("books")
def endhandle():
	print ("scrapy score end!")
sr_doubanbook_score(collection, endhandle)
'''

# ===============
# 库中字段删除
# ===============
def remove_clt_key(dbcollection, keylist, callback = None):
	booklist = funcs.get_dbcolt_list(clt)

	rmkey = dict()
	for key in keylist:
		rmkey[key] = ""
	for book in booklist:
		clt.update(dict(name=book["name"]), {"$unset":rmkey})
	if hasattr(callback, "__call__"):
		callback()

